/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * GUIConversa.java
 *
 * Created on 05/11/2010, 04:39:59
 */
package ifpb.pod.cliente.visao;

import ifpb.pod.cliente.funcionalidades.ArmazemDeConversas;
import ifpb.pod.cliente.funcionalidades.FachadaCliente;
import ifpb.pod.model.ContaUsuario;
import ifpb.pod.model.Contato;
import ifpb.pod.model.Usuario;
import ifpb.pod.remote.ClienteRemote;
import java.awt.event.KeyEvent;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JScrollBar;

/**
 *
 * @author Diogenes
 */
public class GUIConversa extends javax.swing.JFrame implements Runnable {

    /** Creates new form GUIConversa */
    private Contato remetente;
    private final String SEPARADOR = " >>> ";
    private List<ClienteRemote> clientes;
    private FachadaCliente fachada;
    private Boolean mediador;

    /** Creates new form GUIConversa */
    public GUIConversa(Contato remetente, ClienteRemote cliente) {
        initComponents();
        this.mediador = true;
        this.remetente = remetente;
        this.clientes = new ArrayList<ClienteRemote>();
        addClienteRemoto(cliente);
        this.fachada = FachadaCliente.getInstance();
        repaintContatosDaConversa();
        inputTextArea.requestFocus();
    }

    public String getStringContatos() {
        StringBuffer buffer = new StringBuffer();
        try {

            for (ClienteRemote clienteRemote : clientes) {
                buffer.append(clienteRemote.getContato());
            }
        } catch (RemoteException ex) {
            ex.printStackTrace();
        }
        return buffer.toString();
    }

    private void repaintContatosDaConversa() {
        try {
            DefaultListModel model = new DefaultListModel();
            contatosDaConversa.setModel(model);
            for (ClienteRemote clienteRemote : clientes) {
                model.addElement(clienteRemote.getContato());
            }
        } catch (RemoteException ex) {
            ex.printStackTrace();
        }
    }

    public void setCliente(ClienteRemote cliente) {
        addClienteRemoto(cliente);
    }

    public Boolean addClienteRemoto(ClienteRemote clienteRemote) {
        repaintContatosDaConversa();
        if (!this.clientes.contains(clienteRemote)) {
            return this.clientes.add(clienteRemote);
        }
        return Boolean.FALSE;

    }

    public void setMediador(Boolean mediador) {
        this.mediador = mediador;
        repaintContatosDaConversa();
    }

    public  String getKeyConversas() {
        StringBuffer buffer = new StringBuffer();
        for (ClienteRemote cliente : clientes) {
            buffer.append(cliente.toString());
        }
        return buffer.toString();

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lDestinatario = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        msgScrollPane = new javax.swing.JScrollPane();
        msgPane = new javax.swing.JTextArea();
        jScrollPane2 = new javax.swing.JScrollPane();
        inputTextArea = new javax.swing.JTextArea();
        jScrollPane1 = new javax.swing.JScrollPane();
        contatosDaConversa = new javax.swing.JList();
        jToolBar1 = new javax.swing.JToolBar();
        addAmigo = new javax.swing.JButton();
        bArquivo = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        lDestinatario.setFont(new java.awt.Font("Malgun Gothic", 0, 36));
        lDestinatario.setText("Destinatario");

        msgScrollPane.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        msgPane.setColumns(20);
        msgPane.setEditable(false);
        msgPane.setLineWrap(true);
        msgPane.setRows(5);
        msgPane.setWrapStyleWord(true);
        msgScrollPane.setViewportView(msgPane);

        inputTextArea.setColumns(20);
        inputTextArea.setLineWrap(true);
        inputTextArea.setRows(5);
        inputTextArea.setWrapStyleWord(true);
        inputTextArea.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                inputTextAreaKeyPressed(evt);
            }
        });
        jScrollPane2.setViewportView(inputTextArea);

        contatosDaConversa.setBorder(javax.swing.BorderFactory.createTitledBorder("Você está conversando com:"));
        contatosDaConversa.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        contatosDaConversa.setOpaque(false);
        jScrollPane1.setViewportView(contatosDaConversa);

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);

        addAmigo.setText("Add amigo a conversa");
        addAmigo.setFocusable(false);
        addAmigo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        addAmigo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        addAmigo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addAmigoActionPerformed(evt);
            }
        });
        jToolBar1.add(addAmigo);

        bArquivo.setText("Enviar Arquivo");
        bArquivo.setFocusable(false);
        bArquivo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        bArquivo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        bArquivo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bArquivoActionPerformed(evt);
            }
        });
        jToolBar1.add(bArquivo);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 694, Short.MAX_VALUE)
                    .addComponent(lDestinatario)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 694, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 177, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(msgScrollPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 507, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(lDestinatario)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(msgScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 332, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void inputTextAreaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_inputTextAreaKeyPressed
        if (!inputTextArea.getText().trim().equals("")) {
            if (evt.getKeyChar() == KeyEvent.VK_ENTER) {

                if (evt.isShiftDown()) {
                    inputTextArea.append(" \n");
                } else {
                    //Send The Message...
                    boolean cleanTextField = false;
                    try {
                        sendMessage(inputTextArea.getText());
                        cleanTextField = true;
                        scroll();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        cleanTextField = false;
                    } finally {
                        if (cleanTextField) {
                            inputTextArea.setText(null);

                        }
                    }
                }
            }
        }
}//GEN-LAST:event_inputTextAreaKeyPressed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        try {
            //        ArmazemDeConversas.getInstance().removeConversa(this.clientes.get(0).getContato()));
            ArmazemDeConversas armazemDeConversas = ArmazemDeConversas.getInstance();
//            if (this.clientes.size() == 1) {
                armazemDeConversas.removeConversa(this.clientes.get(0).getContato());
//            } else {
                System.out.println("sair do grupo e não receber mais mensagens");
//            }

        } catch (RemoteException ex) {
            ex.printStackTrace();
        }

    }//GEN-LAST:event_formWindowClosed

    private void addAmigoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addAmigoActionPerformed
        // TODO add your handling code here:       
        List<Contato> cSelecionados = new ArrayList<Contato>();


        ContaUsuario uc = new ContaUsuario();
        uc.setLogin(remetente.getLogin());
        Usuario u = fachada.buscarUsuario(uc);
        List<Contato> contatos = fachada.getAmigosOnline(u);

        for (Contato outroContato : contatos) {
            cSelecionados.add(outroContato);
        }
        for (ClienteRemote remote : clientes) {
            try {
                cSelecionados.remove(remote.getContato());
            } catch (RemoteException ex) {
                ex.printStackTrace();
            }
        }

        System.out.println(cSelecionados.size() + "oiasodsodis");
        for (Contato contato : cSelecionados) {
            System.out.println("Foi" + contato);

        }

        GUISeletorAmigoConversaGrupo seletor = new GUISeletorAmigoConversaGrupo(remetente, cSelecionados, clientes);
        seletor.setVisible(true);

    }//GEN-LAST:event_addAmigoActionPerformed

    private void bArquivoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bArquivoActionPerformed
        new GUIArquivo().setVisible(true);
    }//GEN-LAST:event_bArquivoActionPerformed

// public synchronized void addWindowListener(WindowListener l){
////     public void windowClosing(WindowEvent evt) {
////        if (JOptionPane.showConfirmDialog(null,"Deseja sair")==JOptionPane.OK_OPTION){
////            salvarDados();  }
////}
////});
// }
//    @Override
//    public void setVisible(boolean b) {
//        msgPane.setText(null);
//        inputTextArea.setText(null);
//        inputTextArea.requestFocus();
//        super.setVisible(b);
//
//    }
    private String montaMensagemParaEnviar(String text) {
        StringBuffer bufer = new StringBuffer();
        bufer.append(remetente.getLogin());
        bufer.append(SEPARADOR);
        try {
            if (clientes.size() == 1) {
                bufer.append(clientes.get(0).getContato().getLogin());
            } else {
                bufer.append("Todos");
            }
        } catch (RemoteException ex) {
            ex.printStackTrace();
        }
        bufer.append("\n");
        bufer.append(text.trim());
        bufer.append("\n");
        bufer.append("\n");
        return bufer.toString();
    }

    private void sendMessage(String text) {
        text = montaMensagemParaEnviar(text);
        try {
            for (ClienteRemote clienteRemote : clientes) {
                if(clientes.size()==1){
                     fachada.conversar(this.remetente, clienteRemote.getContato());
                }else{
//                    fachada.conversarGrupo(remetente, remetente, null, mediador);
                }
               
                clienteRemote.receberMensagem(this.remetente, text);
            }
            this.msgPane.append(text);

        } catch (RemoteException ex) {
            ex.printStackTrace();
        }

    }

    public void receberMensagem(String mensagem) {
        this.msgPane.append(mensagem);
        scroll();

    }

    public void run() {
        System.out.println("To ecutando");
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addAmigo;
    private javax.swing.JButton bArquivo;
    private javax.swing.JList contatosDaConversa;
    private javax.swing.JTextArea inputTextArea;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JLabel lDestinatario;
    private javax.swing.JTextArea msgPane;
    private javax.swing.JScrollPane msgScrollPane;
    // End of variables declaration//GEN-END:variables

    private void scroll() {
        msgScrollPane.setAutoscrolls(true);
        JScrollBar vbar = msgScrollPane.getVerticalScrollBar();
        if ((vbar.getValue() + vbar.getVisibleAmount()) == vbar.getMaximum()) {
            msgPane.setCaretPosition(msgPane.getDocument().getLength());
        } else {
            System.out.println("no else");
            msgPane.setCaretPosition(msgPane.getDocument().getLength());
        }
    }
}
